package com.xwd.controller;

import com.xwd.constants.AjaxResult;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class GlobalControllerAdvice {

    static Logger logger = Logger.getLogger(GlobalControllerAdvice.class);

    //运行时异常处理
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public AjaxResult handlerException(Exception ex){
        String message = ex.getMessage();
        logger.error(message);
        return AjaxResult.error(message);
    }

    //参数校验异常处理---begin

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public AjaxResult handlerValidationException(BindException ex){
        logger.error("参数校验发生异常{}",ex);
        return AjaxResult.error(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        logger.error("",ex);
        //获取异常信息
        BindingResult bindingResult = ex.getBindingResult();
        //判断异常中是否存在异常信息
        if (bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            if (Objects.nonNull(allErrors) && !allErrors.isEmpty()){
                FieldError fieldError = (FieldError)allErrors.get(0);
                return AjaxResult.error(fieldError.getDefaultMessage());
            }
        }
        return AjaxResult.error("MethodArgumentNotValidException:请求参数不合法!");
    }

    //参数校验异常处理---end
}
